//
//  CompleteRegisterInfoViewController.m
//  atXiaoGeBClient
//
//  Created by Linyu Niu on 17/04/2018.
//  Copyright © 2018 Linyu Niu. All rights reserved.
//

#import "CompleteRegisterInfoViewController.h"
#import "XLIDScanViewController.h"

#import "VerifyCourierByExpressNumberViewController.h"

@interface CompleteRegisterInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    XLScanResultModel * idModel;
    UIImage * aSideImage;
    UIImage * bSideImage;
    UITableView * completeTableView;
    NSString * idNumber;
    UIImage * chooseImage;
    NSString * idCardName;
    BOOL isCourier;
    UIImagePickerController * imgPickerController;
    NSMutableDictionary * subData;
}
@end

@implementation CompleteRegisterInfoViewController
@synthesize userId;

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"userid----->%@",userId);
    subData = [[NSMutableDictionary alloc]init];
    __weak CompleteRegisterInfoViewController * weakSelf = self;
    UIView * navView = [[CTMediator sharedInstance] navgationHeadViewInTargetView:self.view params:[NSDictionary dictionaryWithObjectsAndKeys:@"完善信息",@"title", nil] leftAction:^(UIButton * sender){
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } rightAction:nil];
    
    completeTableView = [self addTableViewInView:self.view frame:CGRectMake(0, navView.frame.origin.y + navView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height) delegateAndDataSource:self];
    completeTableView.backgroundColor = [UIColor colorWithRed:238.0 / 255.0 green:238.0 / 255.0 blue:238.0 / 255.0 alpha:1.0];
}
-(void)isSender:(UISwitch *)s{
    isCourier = s.on;
}

-(void)nextStop{
//    courierName
    
    if(aSideImage && bSideImage && chooseImage){
        
        dispatch_group_t group = dispatch_group_create();
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        
        [self startLoadingView:self.view];
        __block BOOL sucessA = NO;
        __block BOOL sucessB = NO;
        __block BOOL sucessC = NO;
        __weak CompleteRegisterInfoViewController * weakSelf = self;
        
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            [[CTMediator sharedInstance] uploadUserHeadImage:chooseImage userId:userId registIs:YES block:^(NSDictionary * dic){
                
                sucessC = [weakSelf isSuccess:dic];
                if(!sucessC){
                    [weakSelf stopLoadingView:weakSelf.view needShowMsg:YES result:dic];
                }
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }) ;
        
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            [[CTMediator sharedInstance] uploadIDCard:@"0" image:aSideImage cardNumber:idModel.code name:idModel.name courierId:userId registIs:1 block:^(NSDictionary * dic){
                sucessA = [weakSelf isSuccess:dic];
                if(!sucessA){
                    [weakSelf stopLoadingView:weakSelf.view needShowMsg:YES result:dic];
                }
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }) ;
        
        
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [[CTMediator sharedInstance] uploadIDCard:@"1" image:bSideImage cardNumber:idModel.code name:idModel.name courierId:userId registIs:1 block:^(NSDictionary * dic){
                sucessB = [weakSelf isSuccess:dic];
                if(!sucessB){
                    [weakSelf stopLoadingView:weakSelf.view needShowMsg:YES result:dic];
                }
                dispatch_semaphore_signal(semaphore);
            }];
            
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }) ;
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            
            if(sucessA && sucessB && sucessC){
//                [self dismissViewControllerAnimated:YES completion:nil];
                [self stopLoadingView:self.view needShowMsg:NO result:nil];
                VerifyCourierByExpressNumberViewController * controller = [[VerifyCourierByExpressNumberViewController alloc]init];
                controller.courierID = userId;
                controller.isRegister = YES;
                [self.navigationController pushViewController:controller animated:YES];
            }else{
                [self stopLoadingView:self.view needShowMsg:YES result:[NSDictionary dictionaryWithObjectsAndKeys:@"上传失败，请重试",@"msg", nil]];
            }
        });
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ElementTableViewCell * cell = (ElementTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    return cell.cellHeight;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ElementTableViewCell * cell = [[ElementTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    if ([indexPath section] == 0) {
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor colorWithRed:51.0 / 255.0 green:51.0 / 255.0 blue:51.0 / 255.0 alpha:1.0];
        cell.cellHeight = 50;
        if ([indexPath row] == 0) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = @"头像";
            UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(tableView.frame.size.width - 70, (cell.cellHeight - 40 ) / 2, 40, 40)];
            [cell addSubview:imgView];
            if (chooseImage) {
                imgView.image = chooseImage;
            }
//            cell.cellHeight = 0;
        }else if([indexPath row] == 1){
            cell.textLabel.text = @"我是快递员";
            UISwitch * s = [[UISwitch alloc]initWithFrame:CGRectMake(tableView.frame.size.width - 70, (cell.cellHeight - 30) / 2, 45, 30)];
            s.on = isCourier;
            [s addTarget:self action:@selector(isSender:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:s];
        }
        
        if ([indexPath row] == 0) {
            UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, cell.cellHeight - 1.0, tableView.frame.size.width, 0.5)];
            lineView.backgroundColor = [UIColor colorWithRed:222.0 / 255.0 green:222.0 / 255.0 blue:222.0 / 255.0 alpha:1.0];
            [cell addSubview:lineView];
        }
    }else if([indexPath section] == 1){
        if ([indexPath row] < 2) {
            UIImageView * imgView = [[UIImageView alloc]init];
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            imgView.frame = CGRectMake(20, 15, tableView.frame.size.width - 40, 160);
            if ([indexPath row] == 0) {
                imgView.image = [UIImage imageNamed:@"id_a_side"];
                if (aSideImage) {
                    imgView.image = aSideImage;
                }
            }else{
                imgView.image = [UIImage imageNamed:@"id_b_side"];
                if (bSideImage) {
                    imgView.image = bSideImage;
                }
            }
            
            [cell addSubview:imgView];
            cell.cellHeight = imgView.frame.origin.y * 2 + imgView.frame.size.height;
        }else if([indexPath row] == 2){
            UIButton * nextButton = [[CTMediator sharedInstance] commonOrangeButton:CGRectMake(30, 10, tableView.frame.size.width - 60, 40) title:@"下一步" delegate:self action:@selector(nextStop)];
            [cell addSubview:nextButton];
            cell.cellHeight = nextButton.frame.origin.y * 2 + nextButton.frame.size.height;
        }
    }
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 15)];
    return v;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 3;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([indexPath section] == 0){
        if ([indexPath row] == 0) {
            
            __weak CompleteRegisterInfoViewController * weakSelf = self;
            UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action){
                [weakSelf showImgPicker:UIImagePickerControllerSourceTypeCamera];
            }];
            
            UIAlertAction * photoAction = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action){
                [weakSelf showImgPicker:UIImagePickerControllerSourceTypePhotoLibrary];
            }];
            
            UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action){
                
            }];
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
            [alert addAction:cameraAction];
            [alert addAction:photoAction];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }else if ([indexPath section] == 1) {
        if([indexPath section] == 1){
            if ([indexPath row] != 2){
                /**
                 
                 */
                XLIDScanViewController * controller = [[XLIDScanViewController alloc]init];
                controller.navigationController.navigationBarHidden = YES;
                controller.finishBlock = ^(XLScanResultModel *model) {
                    
                    if(model.code){//正面
                        idModel = model;
                        aSideImage = model.idImage;
                        idNumber = model.code;
                        idCardName = model.name;
                    }else{
                        bSideImage = model.idImage;
                    }
                    [tableView reloadData];
                };
                
                controller.view.backgroundColor = [UIColor whiteColor];
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
}

-(void)showImgPicker:(NSInteger)type{
    if (!imgPickerController) {
        imgPickerController = [[UIImagePickerController alloc]init];
        imgPickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        imgPickerController.delegate = self;
        imgPickerController.allowsEditing = YES;
    }
    imgPickerController.sourceType = type;
    [self presentViewController:imgPickerController animated:YES completion:nil];
}



#pragma mark-ImgPicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    chooseImage = image;
    [completeTableView reloadData];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



@end
